package archive

import (
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
	"strings"
)

const separator = string(filepath.Separator)

var repl = strings.NewReplacer("/", separator, "\\", separator)

func GetKindByExt(fn string) (archive Kind, compress Kind, err error) {
	if fn == "" {
		return
	}
	var aExt string
	cExt := strings.ToLower(filepath.Ext(fn))
	if cExt != "" {
		aExt = strings.ToLower(filepath.Ext(fn[:len(fn)-len(cExt)]))
	}

	if aExt == ".tar" {
		archive = TAR
	}

	switch cExt {
	case ".zip":
		compress = ZIP
		archive = ZIP
	case ".gz":
		compress = GZ
	case ".zst":
		compress = ZST
	case ".xz":
		compress = XZ
	case ".snz":
		compress = SNZ
	default:
		err = fmt.Errorf("unknown file ext: %s%s", aExt, cExt)
	}

	return
}

// readToFile 读取流并保存到文件
func readToFile(r io.Reader, target string, mode os.FileMode) error {
	dir := filepath.Dir(target)
	if err := os.MkdirAll(dir, 0755); err != nil {
		return err
	}

	w, err := os.OpenFile(target, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode)
	if err != nil {
		return err
	}
	_, err = io.Copy(w, r)
	_ = w.Close()
	return err
}

func getTargetFilePath(targetDIR, name string, trimRoot bool) string {
	name = strings.Trim(repl.Replace(name), separator)
	if trimRoot {
		if index := strings.Index(name, separator); index != -1 {
			name = name[index+len(separator):]
		} else {
			name = ""
		}
	}
	if name == "" {
		return ""
	}
	return filepath.Join(targetDIR, name)
}

func tryClose(closers ...io.Closer) {
	for _, closer := range closers {
		if closer != nil {
			if err := closer.Close(); err != nil {
				log.Println(err)
			}
		}
	}
}
